import _ from 'lodash'

export const treeConvertToArr = (tree:any[]) => {
  let arr:any[] = []
  const result:any[] = []
  arr = arr.concat(tree)
  while (arr.length) {
    const first = arr.shift() // 弹出第一个元素
    if (first.children) {
      // 如果有children
      arr = arr.concat(first.children)
      delete first.children
    }
    result.push(first)
  }
  return result
}

// 一维数组生成树结构数据
export const toTree = (
  arr:any = [],
  key_id = 'id',
  key_pid = 'parentId',
  children = 'children'
) => {
  const data = _.cloneDeep(arr)
  const tree:any = []
  for (let i = 0; i < data.length; i++) {
    const item:any = data[i]
    const parentId = item[key_pid]
    const parent:any = data.find((item:any) => item[key_id] === parentId)
    if (parent) {
      if (!parent[children]) {
        parent[children] = []
      }
      parent[children].push(item)
    } else {
      if (!item[children]) {
        item[children] = []
      }
      tree.push(item)
    }
  }
  return tree
}
